import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestRegressor
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import train_test_split
from sklearn.metrics import mean_absolute_error, r2_score
from src.models.database import db, HistoricalData, PredictionTask, PredictionResult
from src.models.metaso_data import MetasoQueryData
from src.services.llm_service import LLMService
import json
import threading
from datetime import datetime
import time

class PredictionService:
    """预测分析服务"""
    
    def __init__(self):
        self.llm_service = LLMService()
        self.running_tasks = {}
        
    def start_prediction_task(self, task_id):
        """启动预测任务（异步）"""
        from flask import current_app
        
        def run_task():
            # 在新线程中创建应用上下文
            with current_app.app_context():
                try:
                    print(f"🚀 线程启动，开始执行任务: {task_id}")
                    self._execute_prediction_task(task_id)
                    print(f"✅ 线程任务执行完成: {task_id}")
                except Exception as e:
                    print(f"❌ 线程任务执行失败: {task_id}, 错误: {str(e)}")
                    import traceback
                    traceback.print_exc()
                    self._handle_task_error(task_id, str(e))
        
        # 在新线程中运行任务
        thread = threading.Thread(target=run_task)
        thread.daemon = True
        thread.start()
        
        self.running_tasks[task_id] = thread
        print(f"🔄 异步线程已启动，任务ID: {task_id}")
        
    def _execute_prediction_task(self, task_id):
        """执行预测任务"""
        print(f"🚀 开始执行预测任务: {task_id}")
        
        task = PredictionTask.query.filter_by(task_id=task_id).first()
        if not task:
            print(f"❌ 任务不存在: {task_id}")
            raise ValueError(f"任务不存在: {task_id}")
        
        print(f"📋 任务信息: {task.task_name} (类型: {task.task_type})")
        
        try:
            # 更新任务状态
            task.status = 'running'
            task.started_at = datetime.utcnow()
            task.progress = 0
            task.current_step = '准备数据'
            db.session.commit()
            
            # 获取任务参数
            company_ids = json.loads(task.company_ids) if task.company_ids else []
            product_ids = json.loads(task.product_ids) if task.product_ids else []
            
            # 处理预测年份参数
            if isinstance(task.prediction_years, str):
                try:
                    prediction_years = json.loads(task.prediction_years)
                    if not isinstance(prediction_years, list):
                        prediction_years = [prediction_years]
                except json.JSONDecodeError:
                    # 如果不是JSON格式，可能是单个年份
                    prediction_years = [int(task.prediction_years)]
            else:
                prediction_years = [task.prediction_years] if task.prediction_years else [2025]
            
            # 解析集团战略增速参数（如果存在）
            strategic_growth_rates = {}
            if hasattr(task, 'description') and task.description:
                try:
                    task_params = json.loads(task.description)
                    strategic_growth_rates = task_params.get('strategic_growth_rates', {})
                except:
                    pass
            
            # 根据任务类型选择不同的处理流程
            if task.task_type == 'group_prediction':
                # 集团预测流程
                task.progress = 10
                task.current_step = '执行集团预测'
                db.session.commit()
                
                predictions_with_ai = self._execute_group_prediction(task, prediction_years, strategic_growth_rates)
                
                task.progress = 90
                task.current_step = '保存结果'
                db.session.commit()
            else:
                # 原有的产品预测流程
                # 步骤1: 准备历史数据
                historical_data = self._prepare_historical_data(company_ids, product_ids)
                task.progress = 20
                task.current_step = '构建预测模型'
                db.session.commit()
                
                # 步骤2: 构建和训练预测模型
                models = self._build_prediction_models(historical_data)
                task.progress = 40
                task.current_step = '生成预测结果'
                db.session.commit()
                
                # 步骤3: 生成预测结果
                predictions = self._generate_predictions(models, historical_data, prediction_years)
                task.progress = 60
                task.current_step = '计算差异分析'
                db.session.commit()
                
                # 步骤4: 计算差异分析
                predictions_with_variance = self._calculate_variance_analysis(predictions, historical_data)
                task.progress = 80
                task.current_step = 'AI影响因素分析'
                db.session.commit()
                
                # 步骤5: LLM影响因素分析
                predictions_with_ai = self._generate_ai_analysis(predictions_with_variance, historical_data)
                task.progress = 90
                task.current_step = '保存结果'
                db.session.commit()
            
            # 步骤6: 保存预测结果
            print(f"💾 开始保存预测结果，共 {len(predictions_with_ai)} 条记录")
            self._save_prediction_results(task_id, predictions_with_ai)
            print(f"✅ 预测结果保存完成")
            
            # 完成任务
            task.status = 'completed'
            task.progress = 100
            task.current_step = '任务完成'
            task.completed_at = datetime.utcnow()
            db.session.commit()
            
            print(f"🎉 任务执行完成: {task_id}")
            
        except Exception as e:
            print(f"❌ 任务执行失败: {task_id}, 错误: {str(e)}")
            import traceback
            print("详细错误信息:")
            print(traceback.format_exc())
            
            task.status = 'failed'
            task.error_message = str(e)
            task.completed_at = datetime.utcnow()
            db.session.commit()
            raise e
    
    def _prepare_historical_data(self, company_ids, product_ids):
        """准备历史数据"""
        query = HistoricalData.query.filter(HistoricalData.company_id.in_(company_ids))
        
        if product_ids:
            query = query.filter(HistoricalData.product_id.in_(product_ids))
        
        records = query.order_by(
            HistoricalData.company_id,
            HistoricalData.product_id,
            HistoricalData.year
        ).all()
        
        # 转换为DataFrame
        data = []
        for record in records:
            data.append({
                'company_id': record.company_id,
                'company_name': record.company_name,
                'product_id': record.product_id,
                'product_name': record.product_name,
                'year': record.year,
                'sales_volume': record.sales_volume,
                'avg_price': record.avg_price,
                'sales_amount': record.sales_amount,
                'unit_cost': record.unit_cost,
                'unit_profit': record.unit_profit,
                'yoy_growth_rate': record.yoy_growth_rate or 0,
                'cagr': record.cagr or 0
            })
        
        return pd.DataFrame(data)
    
    def _build_prediction_models(self, historical_data):
        """构建预测模型"""
        models = {}
        
        # 按产品分组构建模型
        for (company_id, product_id), group in historical_data.groupby(['company_id', 'product_id']):
            if len(group) < 3:  # 至少需要3年数据
                continue
            
            # 特征工程
            features = self._create_features(group)
            
            if len(features) < 2:
                continue
            
            # 构建多个目标变量的模型
            targets = ['sales_volume', 'avg_price', 'sales_amount', 'unit_cost', 'unit_profit']
            product_models = {}
            
            for target in targets:
                try:
                    X = features.drop(columns=[target] + ['year'])
                    y = features[target]
                    
                    if len(X) < 2:
                        continue
                    
                    # 训练模型
                    model = RandomForestRegressor(n_estimators=100, random_state=42)
                    model.fit(X, y)
                    
                    # 计算模型准确率
                    y_pred = model.predict(X)
                    accuracy = r2_score(y, y_pred)
                    
                    product_models[target] = {
                        'model': model,
                        'scaler': StandardScaler().fit(X),
                        'feature_names': X.columns.tolist(),
                        'accuracy': accuracy
                    }
                    
                except Exception as e:
                    print(f"构建模型失败 {company_id}-{product_id}-{target}: {str(e)}")
                    continue
            
            if product_models:
                models[(company_id, product_id)] = product_models
        
        return models
    
    def _create_features(self, group_data):
        """创建特征"""
        df = group_data.copy().sort_values('year')
        
        # 滞后特征
        for col in ['sales_volume', 'avg_price', 'sales_amount', 'unit_cost', 'unit_profit']:
            df[f'{col}_lag1'] = df[col].shift(1)
            df[f'{col}_lag2'] = df[col].shift(2)
        
        # 移动平均特征
        for col in ['sales_volume', 'avg_price', 'sales_amount']:
            df[f'{col}_ma2'] = df[col].rolling(window=2).mean()
            df[f'{col}_ma3'] = df[col].rolling(window=3).mean()
        
        # 趋势特征
        df['year_trend'] = df['year'] - df['year'].min()
        
        # 删除包含NaN的行
        df = df.dropna()
        
        return df
    
    def _generate_predictions(self, models, historical_data, prediction_years):
        """生成预测结果"""
        predictions = []
        
        for (company_id, product_id), product_models in models.items():
            # 获取该产品的历史数据
            product_data = historical_data[
                (historical_data['company_id'] == company_id) & 
                (historical_data['product_id'] == product_id)
            ].copy()
            
            if len(product_data) == 0:
                continue
            
            # 获取最新年份的数据作为基准
            latest_data = product_data.iloc[-1]
            
            for year in prediction_years:
                year = int(year)
                
                # 创建预测特征
                prediction_features = self._create_prediction_features(
                    product_data, latest_data, year
                )
                
                # 对每个目标变量进行预测
                prediction_result = {
                    'company_id': company_id,
                    'company_name': latest_data['company_name'],
                    'product_id': product_id,
                    'product_name': latest_data['product_name'],
                    'prediction_year': year
                }
                
                confidence_scores = []
                
                for target, model_info in product_models.items():
                    try:
                        model = model_info['model']
                        feature_names = model_info['feature_names']
                        
                        # 确保特征顺序一致
                        X_pred = prediction_features[feature_names].values.reshape(1, -1)
                        
                        # 预测
                        pred_value = model.predict(X_pred)[0]
                        
                        # 确保预测值为正数
                        pred_value = max(pred_value, 0)
                        
                        prediction_result[f'predicted_{target}'] = pred_value
                        confidence_scores.append(model_info['accuracy'])
                        
                    except Exception as e:
                        print(f"预测失败 {company_id}-{product_id}-{target}: {str(e)}")
                        # 使用历史平均值作为备选
                        avg_value = product_data[target].mean()
                        prediction_result[f'predicted_{target}'] = avg_value
                        confidence_scores.append(0.5)
                
                # 计算平均置信度
                prediction_result['confidence_score'] = np.mean(confidence_scores) if confidence_scores else 0.5
                
                predictions.append(prediction_result)
        
        return predictions
    
    def _create_prediction_features(self, historical_data, latest_data, prediction_year):
        """创建预测特征"""
        # 基于最新数据创建特征
        features = {}
        
        # 滞后特征（使用最新年份的数据）
        for col in ['sales_volume', 'avg_price', 'sales_amount', 'unit_cost', 'unit_profit']:
            features[f'{col}_lag1'] = latest_data[col]
            if len(historical_data) >= 2:
                features[f'{col}_lag2'] = historical_data.iloc[-2][col]
            else:
                features[f'{col}_lag2'] = latest_data[col]
        
        # 移动平均特征
        for col in ['sales_volume', 'avg_price', 'sales_amount']:
            if len(historical_data) >= 2:
                features[f'{col}_ma2'] = historical_data[col].tail(2).mean()
            else:
                features[f'{col}_ma2'] = latest_data[col]
            
            if len(historical_data) >= 3:
                features[f'{col}_ma3'] = historical_data[col].tail(3).mean()
            else:
                features[f'{col}_ma3'] = latest_data[col]
        
        # 趋势特征
        min_year = historical_data['year'].min()
        features['year_trend'] = prediction_year - min_year
        
        return pd.Series(features)
    
    def _calculate_variance_analysis(self, predictions, historical_data):
        """计算差异分析"""
        for prediction in predictions:
            try:
                # 获取基准年份（最新年份）的数据
                base_data = historical_data[
                    (historical_data['company_id'] == prediction['company_id']) & 
                    (historical_data['product_id'] == prediction['product_id'])
                ].iloc[-1]
                
                # 计算各种差异
                # 量差 = (预测销量 - 基准销量) * 基准单价
                volume_diff = prediction['predicted_sales_volume'] - base_data['sales_volume']
                prediction['volume_variance'] = volume_diff * base_data['avg_price']
                
                # 价差 = (预测单价 - 基准单价) * 预测销量
                price_diff = prediction['predicted_avg_price'] - base_data['avg_price']
                prediction['price_variance'] = price_diff * prediction['predicted_sales_volume']
                
                # 成本差异 = (预测成本 - 基准成本) * 预测销量
                cost_diff = prediction['predicted_unit_cost'] - base_data['unit_cost']
                prediction['cost_variance'] = -cost_diff * prediction['predicted_sales_volume']  # 成本增加为负影响
                
                # 总差异
                prediction['total_variance'] = (
                    prediction['volume_variance'] + 
                    prediction['price_variance'] + 
                    prediction['cost_variance']
                )
                
            except Exception as e:
                print(f"计算差异分析失败: {str(e)}")
                # 设置默认值
                prediction['volume_variance'] = 0
                prediction['price_variance'] = 0
                prediction['cost_variance'] = 0
                prediction['total_variance'] = 0
        
        return predictions
    
    def _generate_ai_analysis(self, predictions, historical_data):
        """生成AI影响因素分析"""
        for prediction in predictions:
            try:
                # 获取该产品的历史数据
                product_history = historical_data[
                    (historical_data['company_id'] == prediction['company_id']) & 
                    (historical_data['product_id'] == prediction['product_id'])
                ]
                
                # 构建分析上下文
                context = {
                    'product_name': prediction['product_name'],
                    'company_name': prediction['company_name'],
                    'prediction_year': prediction['prediction_year'],
                    'historical_trend': self._analyze_historical_trend(product_history),
                    'prediction_summary': {
                        'sales_volume': prediction['predicted_sales_volume'],
                        'avg_price': prediction['predicted_avg_price'],
                        'sales_amount': prediction['predicted_sales_amount'],
                        'unit_cost': prediction['predicted_unit_cost'],
                        'unit_profit': prediction['predicted_unit_profit']
                    },
                    'variance_analysis': {
                        'volume_variance': prediction['volume_variance'],
                        'price_variance': prediction['price_variance'],
                        'cost_variance': prediction['cost_variance'],
                        'total_variance': prediction['total_variance']
                    }
                }
                
                # 调用LLM生成分析
                analysis = self.llm_service.generate_influence_factors_analysis(context)
                prediction['influence_factors_analysis'] = analysis
                
                # 模拟延时
                time.sleep(0.5)
                
            except Exception as e:
                print(f"生成AI分析失败: {str(e)}")
                # 生成默认分析
                prediction['influence_factors_analysis'] = self._generate_default_analysis(prediction)
        
        return predictions
    
    def _analyze_historical_trend(self, product_history):
        """分析历史趋势"""
        if len(product_history) < 2:
            return "数据不足"
        
        # 计算趋势
        sales_trend = product_history['sales_amount'].pct_change().mean() * 100
        volume_trend = product_history['sales_volume'].pct_change().mean() * 100
        price_trend = product_history['avg_price'].pct_change().mean() * 100
        
        return {
            'sales_growth_rate': round(sales_trend, 2),
            'volume_growth_rate': round(volume_trend, 2),
            'price_growth_rate': round(price_trend, 2),
            'years_of_data': len(product_history)
        }
    
    def _generate_default_analysis(self, prediction):
        """生成默认分析"""
        return f"""基于历史数据和预测模型分析，{prediction['product_name']}在{prediction['prediction_year']}年的预测结果如下：

销售预测：预计销售额达到{prediction['predicted_sales_amount']:.1f}万元，销售量{prediction['predicted_sales_volume']:.0f}单位。

主要影响因素：
1. 市场需求变化：基于历史趋势分析，市场需求呈现稳定增长态势
2. 价格策略：平均销售单价预计为{prediction['predicted_avg_price']:.2f}元
3. 成本控制：单位成本预计为{prediction['predicted_unit_cost']:.2f}元

差异分析：总差异为{prediction['total_variance']:.1f}万元，主要来源于量差和价差的综合影响。

建议关注市场变化和成本控制，以确保预测目标的实现。"""
    
    def _save_prediction_results(self, task_id, predictions):
        """保存预测结果"""
        print(f"💾 保存预测结果: 任务ID={task_id}, 结果数量={len(predictions)}")
        
        for i, prediction in enumerate(predictions):
            print(f"📊 保存第 {i+1} 条结果: {prediction.get('sector_name', prediction.get('company_name', 'Unknown'))}")
            
            # 判断是否为集团预测结果
            if 'sector_id' in prediction:
                # 集团预测结果格式
                result = PredictionResult(
                    task_id=task_id,
                    company_id=prediction.get('sector_id', 'unknown'),
                    company_name=prediction.get('sector_name', '未知板块'),
                    product_id='group_prediction',
                    product_name='集团预测',
                    prediction_year=prediction['prediction_year'],
                    predicted_sales_volume=1,  # 集团预测不使用销量概念
                    predicted_avg_price=prediction.get('predicted_sales_revenue', 0),  # 用销售收入字段
                    predicted_sales_amount=prediction.get('predicted_sales_revenue', 0),
                    predicted_unit_cost=0,  # 集团预测不使用成本概念
                    predicted_unit_profit=prediction.get('predicted_net_profit', 0),  # 用净利润字段
                    volume_variance=0,
                    price_variance=0,
                    cost_variance=0,
                    total_variance=0,
                    influence_factors_analysis=prediction.get('analysis_result', ''),
                    confidence_score=prediction.get('confidence_score', 0.85),
                    comprehensive_rate=prediction.get('comprehensive_growth_rate', 0)  # 保存综合增长率
                )
            else:
                # 原有的产品预测结果格式
                result = PredictionResult(
                    task_id=task_id,
                    company_id=prediction['company_id'],
                    company_name=prediction['company_name'],
                    product_id=prediction['product_id'],
                    product_name=prediction['product_name'],
                    prediction_year=prediction['prediction_year'],
                    predicted_sales_volume=prediction['predicted_sales_volume'],
                    predicted_avg_price=prediction['predicted_avg_price'],
                    predicted_sales_amount=prediction['predicted_sales_amount'],
                    predicted_unit_cost=prediction['predicted_unit_cost'],
                    predicted_unit_profit=prediction['predicted_unit_profit'],
                    volume_variance=prediction['volume_variance'],
                    price_variance=prediction['price_variance'],
                    cost_variance=prediction['cost_variance'],
                    total_variance=prediction['total_variance'],
                    influence_factors_analysis=prediction['influence_factors_analysis'],
                    confidence_score=prediction['confidence_score'],
                    comprehensive_rate=prediction.get('comprehensive_growth_rate', None)  # 产品预测可能没有综合增长率
                )
            
            db.session.add(result)
        
        try:
            db.session.commit()
            print(f"✅ 成功保存 {len(predictions)} 条预测结果到数据库")
        except Exception as e:
            print(f"❌ 保存预测结果失败: {str(e)}")
            db.session.rollback()
            raise e
    
    def _handle_task_error(self, task_id, error_message):
        """处理任务错误"""
        try:
            task = PredictionTask.query.filter_by(task_id=task_id).first()
            if task:
                task.status = 'failed'
                task.error_message = error_message
                task.completed_at = datetime.utcnow()
                db.session.commit()
        except Exception as e:
            print(f"处理任务错误失败: {str(e)}")
    
    def cancel_task(self, task_id):
        """取消任务"""
        if task_id in self.running_tasks:
            # 注意：Python线程无法强制终止，这里只是标记
            del self.running_tasks[task_id]
    
    def get_prediction_summary(self, task_id):
        """获取预测结果汇总"""
        try:
            task = PredictionTask.query.filter_by(task_id=task_id).first()
            if not task:
                raise ValueError("任务不存在")
            
            results = PredictionResult.query.filter_by(task_id=task_id).all()
            
            if not results:
                return {'task': task.to_dict(), 'summary': {}}
            
            # 计算汇总统计
            total_predicted_sales = sum(r.predicted_sales_amount for r in results)
            avg_confidence = sum(r.confidence_score for r in results) / len(results)
            total_variance = sum(r.total_variance for r in results)
            
            summary = {
                'total_products': len(results),
                'total_predicted_sales': round(total_predicted_sales, 2),
                'average_confidence': round(avg_confidence, 3),
                'total_variance': round(total_variance, 2),
                'prediction_years': list(set(r.prediction_year for r in results))
            }
            
            return {
                'task': task.to_dict(),
                'summary': summary,
                'results': [r.to_dict() for r in results]
            }
            
        except Exception as e:
            raise e
    
    def get_model_accuracy_stats(self):
        """获取模型准确率统计"""
        try:
            # 这里可以实现更复杂的准确率统计
            # 目前返回模拟数据
            return {
                'overall_accuracy': 0.925,
                'by_product_type': [
                    {'product_type': '药品', 'accuracy': 0.935},
                    {'product_type': '保健品', 'accuracy': 0.915},
                    {'product_type': '医疗器械', 'accuracy': 0.920}
                ],
                'by_prediction_horizon': [
                    {'years_ahead': 1, 'accuracy': 0.945},
                    {'years_ahead': 2, 'accuracy': 0.925},
                    {'years_ahead': 3, 'accuracy': 0.905}
                ]
            }
            
        except Exception as e:
            raise e

    def _calculate_group_development_factor(self, product_history):
        """计算集团发展分解因子"""
        try:
            # 这里应该从集团战略数据中获取，目前使用模拟数据
            # 实际应用中需要接入集团战略数据库
            group_strategy_factor = 0.05  # 假设集团战略支持度5%
            
            return group_strategy_factor
            
        except Exception as e:
            print(f"计算集团发展因子失败: {str(e)}")
            return 0.0
    
    def _calculate_core_business_metrics(self, predictions):
        """计算三大核心指标"""
        for prediction in predictions:
            try:
                # 1. 营业收入 = 主营业务收入 + 其它业务收入
                # 主营业务收入 = 销售本单位产品获得的收入
                main_business_revenue = prediction['adjusted_sales_amount']  # 主营业务收入
                other_business_revenue = main_business_revenue * 0.05  # 假设其它业务收入占主营业务5%
                total_revenue = main_business_revenue + other_business_revenue
                
                # 2. 净利润 = 收入 - 成本 - 费用 - 所得税
                total_cost = prediction['adjusted_sales_volume'] * prediction['predicted_unit_cost']  # 总成本
                operating_expenses = total_revenue * 0.15  # 假设运营费用占收入15%
                income_tax_rate = 0.25  # 假设所得税率25%
                income_tax = (total_revenue - total_cost - operating_expenses) * income_tax_rate
                net_profit = total_revenue - total_cost - operating_expenses - income_tax
                
                # 3. 自营出口收入 = 本单位产品直接销售到境外国家或地区的收入
                # 不包括销售给国内外贸公司转出口的产品收入
                export_ratio = 0.20  # 假设出口比例20%
                direct_export_revenue = main_business_revenue * export_ratio
                
                # 保存三大核心指标
                prediction['core_business_metrics'] = {
                    'total_revenue': {
                        'value': total_revenue,
                        'breakdown': {
                            'main_business_revenue': main_business_revenue,
                            'other_business_revenue': other_business_revenue
                        },
                        'formula': '主营业务收入 + 其它业务收入'
                    },
                    'net_profit': {
                        'value': net_profit,
                        'breakdown': {
                            'total_revenue': total_revenue,
                            'total_cost': total_cost,
                            'operating_expenses': operating_expenses,
                            'income_tax': income_tax
                        },
                        'formula': '收入 - 成本 - 费用 - 所得税'
                    },
                    'direct_export_revenue': {
                        'value': direct_export_revenue,
                        'breakdown': {
                            'export_ratio': export_ratio,
                            'base_revenue': main_business_revenue
                        },
                        'formula': '本单位产品直接销售到境外国家或地区的收入'
                    }
                }
                
                # 计算关键比率
                prediction['key_ratios'] = {
                    'profit_margin': net_profit / total_revenue if total_revenue > 0 else 0,  # 净利率
                    'cost_ratio': total_cost / total_revenue if total_revenue > 0 else 0,     # 成本率
                    'export_ratio': direct_export_revenue / total_revenue if total_revenue > 0 else 0  # 出口比例
                }
                
            except Exception as e:
                print(f"计算三大核心指标失败: {str(e)}")
                # 设置默认值
                prediction['core_business_metrics'] = {
                    'total_revenue': {'value': 0, 'breakdown': {}, 'formula': ''},
                    'net_profit': {'value': 0, 'breakdown': {}, 'formula': ''},
                    'direct_export_revenue': {'value': 0, 'breakdown': {}, 'formula': ''}
                }
                prediction['key_ratios'] = {
                    'profit_margin': 0,
                    'cost_ratio': 0,
                    'export_ratio': 0
                }
        
        return predictions

    def _execute_group_prediction(self, task, prediction_years, strategic_growth_rates):
        """执行集团预测"""
        print(f"\n🏢 ========== 开始执行集团预测 ==========")
        print(f"📋 任务信息:")
        print(f"   - 任务ID: {task.task_id}")
        print(f"   - 任务名称: {task.task_name}")
        print(f"   - 预测年份: {prediction_years}")
        print(f"   - 战略增速配置: {strategic_growth_rates}")
        
        try:
            # 直接使用预测年份列表（前端已经转换为数组）
            year_range = prediction_years if isinstance(prediction_years, list) else [prediction_years]
            print(f"\n🎯 年份范围处理:")
            print(f"   原始输入: {prediction_years}")
            print(f"   处理后范围: {year_range}")
            print(f"   预测年份数量: {len(year_range)}")
            
            # 定义四个板块
            sectors = {
                'human_drug_formulation': '人药制剂板块',
                'human_drug_raw_material': '人药原料板块', 
                'plant_protection': '植保板块',
                'animal_protection': '动保板块'
            }
            
            print(f"\n🏭 业务板块配置:")
            for sector_id, sector_name in sectors.items():
                strategic_rate = strategic_growth_rates.get(sector_id, 0)
                print(f"   - {sector_name} ({sector_id}): {strategic_rate}%")
            
            predictions = []
            total_steps = len(sectors) * len(year_range)
            current_step = 0
            
            for sector_id, sector_name in sectors.items():
                print(f"\n🏭 ========== 开始处理{sector_name} ==========")
                print(f"📊 板块信息: {sector_id} -> {sector_name}")
                
                # 步骤1: 获取历史数据
                task.progress = 10 + (current_step * 80 // total_steps)
                task.current_step = f'处理{sector_name}历史数据'
                db.session.commit()
                print(f"📈 步骤1: 获取{sector_name}历史数据")
                
                historical_data = self._get_sector_historical_data(sector_name)
                print(f"   历史数据获取结果: {historical_data}")
                
                # 步骤2: 获取行业数据
                task.progress = 15 + (current_step * 80 // total_steps)
                task.current_step = f'获取{sector_name}行业数据'
                db.session.commit()
                print(f"🌐 步骤2: 获取{sector_name}行业数据")
                
                industry_data = self._get_sector_industry_data(sector_id)
                print(f"   行业数据获取结果: {industry_data}")
                
                # 步骤3: 计算综合增长率
                strategic_rate = strategic_growth_rates.get(sector_id, 0) / 100  # 转换为小数
                print(f"\n🎯 开始计算{sector_name}综合增长率")
                print(f"📊 战略增速参数: {strategic_growth_rates.get(sector_id, 0)}% -> {strategic_rate:.4f}")
                
                comprehensive_growth_rate = self._calculate_comprehensive_growth_rate(
                    historical_data, industry_data, strategic_rate, sector_name
                )
                
                # 步骤4: 生成预测结果
                for year in year_range:
                    task.progress = 20 + (current_step * 80 // total_steps)
                    task.current_step = f'生成{sector_name}{year}年预测'
                    db.session.commit()
                    
                    prediction = self._generate_sector_prediction(
                        sector_id, sector_name, year, historical_data, 
                        comprehensive_growth_rate, industry_data
                    )
                    predictions.append(prediction)
                    current_step += 1
            
            # 步骤5: 计算集团合计
            task.progress = 90
            task.current_step = '计算集团合计'
            db.session.commit()
            
            print(f"\n🏢 ========== 开始计算集团合计 ==========")
            print(f"📊 板块预测结果汇总:")
            for prediction in predictions:
                print(f"   - {prediction['sector_name']} {prediction['prediction_year']}年: 收入{prediction['predicted_sales_revenue']:.2f}亿元, 利润{prediction['predicted_net_profit']:.2f}亿元")
            
            group_predictions = self._calculate_group_totals(predictions, year_range)
            predictions.extend(group_predictions)
            
            print(f"\n✅ ========== 集团预测完成 ==========")
            print(f"📊 最终结果统计:")
            print(f"   - 总预测结果: {len(predictions)} 条")
            print(f"   - 板块预测: {len(predictions) - len(group_predictions)} 条")
            print(f"   - 集团合计: {len(group_predictions)} 条")
            
            print(f"\n🏢 集团合计结果:")
            for group_pred in group_predictions:
                print(f"   - {group_pred['prediction_year']}年: 总收入{group_pred['predicted_sales_revenue']:.2f}亿元, 总利润{group_pred['predicted_net_profit']:.2f}亿元")
            
            return predictions
            
        except Exception as e:
            print(f"❌ 集团预测执行失败: {str(e)}")
            import traceback
            print("详细错误信息:")
            print(traceback.format_exc())
            raise e

    def _parse_prediction_years(self, year_range_str):
        """解析预测年份范围"""
        if '-' in year_range_str:
            start_year, end_year = year_range_str.split('-')
            return list(range(int(start_year), int(end_year) + 1))
        else:
            return [int(year_range_str)]

    def _get_sector_historical_data(self, sector_name):
        """获取板块历史数据"""
        try:
            # 从historical_data表获取该板块的销售收入和净利润数据
            records = HistoricalData.query.filter(
                HistoricalData.business_unit == sector_name,
                HistoricalData.metric_name.in_(['销售收入', '净利润'])
            ).order_by(HistoricalData.year.desc()).all()
            
            data = {}
            for record in records:
                if record.metric_name not in data:
                    data[record.metric_name] = []
                data[record.metric_name].append({
                    'year': record.year,
                    'value': record.value,
                    'yoy_growth_rate': record.yoy_growth_rate,
                    'cagr': record.cagr
                })
            
            return data
            
        except Exception as e:
            print(f"获取{sector_name}历史数据失败: {str(e)}")
            return {}

    def _get_sector_industry_data(self, sector_id):
        """获取板块行业数据"""
        try:
            # 映射sector_id到数据库中的sector_id
            sector_mapping = {
                'human_drug_formulation': 'pharma_formulations',
                'human_drug_raw_material': 'pharma_apis', 
                'plant_protection': 'plant_protection',
                'animal_protection': 'animal_health'
            }
            
            db_sector_id = sector_mapping.get(sector_id)
            if not db_sector_id:
                return {}
            
            # 获取最新的行业数据
            industry_record = MetasoQueryData.query.filter(
                MetasoQueryData.sector_id == db_sector_id,
                MetasoQueryData.status == 'completed'
            ).order_by(MetasoQueryData.created_at.desc()).first()
            
            if industry_record:
                # 转换行业数据：如果存储的是百分比形式，转换为小数
                industry_cagr = industry_record.industry_cagr or 0.05
                market_stage_cagr = industry_record.market_stage_cagr or 0.05
                
                # 如果值大于1，说明是百分比形式，需要除以100
                if industry_cagr > 1:
                    industry_cagr = industry_cagr / 100
                if market_stage_cagr > 1:
                    market_stage_cagr = market_stage_cagr / 100
                
                return {
                    'industry_cagr': industry_cagr,
                    'market_stage_cagr': market_stage_cagr,
                    'analysis_result': industry_record.analysis_result
                }
            else:
                # 使用默认值
                return {
                    'industry_cagr': 0.05,  # 默认5%
                    'market_stage_cagr': 0.05,  # 默认5%
                    'analysis_result': '暂无行业分析数据'
                }
                
        except Exception as e:
            print(f"获取{sector_id}行业数据失败: {str(e)}")
            return {
                'industry_cagr': 0.05,
                'market_stage_cagr': 0.05,
                'analysis_result': '数据获取失败'
            }

    def _calculate_comprehensive_growth_rate(self, historical_data, industry_data, strategic_rate, sector_name):
        """计算综合增长率
        g = (g1 × 50%) + (g2 × 15%) + (g3 × 25%) + (g4 × 10%)
        """
        try:
            print(f"\n🧮 开始计算{sector_name}综合增长率")
            print(f"📊 输入参数:")
            print(f"   - 战略增速: {strategic_rate * 100:.2f}%")
            print(f"   - 行业数据: {industry_data}")
            print(f"   - 历史数据: {historical_data}")
            
            # g1: 行业平均增速 (权重50%)
            g1 = industry_data.get('industry_cagr', 0.05)
            print(f"\n📈 g1 - 行业平均增速 (权重50%):")
            print(f"   原始值: {g1}")
            print(f"   百分比: {g1 * 100:.2f}%")
            print(f"   加权值: {g1 * 0.5 * 100:.2f}%")
            
            # g2: 本单位历史增速 (权重15%)
            g2 = 0.05  # 默认值
            if '销售收入' in historical_data and historical_data['销售收入']:
                # 使用最新的CAGR数据
                latest_record = historical_data['销售收入'][0]  # 已按年份降序排列
                g2 = latest_record.get('cagr', 0.05) or 0.05
                g2 = g2 / 100 if g2 > 1 else g2  # 转换为小数
                print(f"\n📊 g2 - 本单位历史增速 (权重15%):")
                print(f"   历史记录: {latest_record}")
                print(f"   原始CAGR: {latest_record.get('cagr', 0.05)}")
                print(f"   转换后值: {g2}")
                print(f"   百分比: {g2 * 100:.2f}%")
                print(f"   加权值: {g2 * 0.15 * 100:.2f}%")
            else:
                print(f"\n📊 g2 - 本单位历史增速 (权重15%):")
                print(f"   无历史数据，使用默认值: {g2}")
                print(f"   百分比: {g2 * 100:.2f}%")
                print(f"   加权值: {g2 * 0.15 * 100:.2f}%")
            
            # g3: 市场阶段预期 (权重25%)
            g3 = industry_data.get('market_stage_cagr', 0.05)
            print(f"\n🎯 g3 - 市场阶段预期 (权重25%):")
            print(f"   原始值: {g3}")
            print(f"   百分比: {g3 * 100:.2f}%")
            print(f"   加权值: {g3 * 0.25 * 100:.2f}%")
            
            # g4: 集团战略目标 (权重10%)
            g4 = strategic_rate
            print(f"\n🏢 g4 - 集团战略目标 (权重10%):")
            print(f"   原始值: {g4}")
            print(f"   百分比: {g4 * 100:.2f}%")
            print(f"   加权值: {g4 * 0.1 * 100:.2f}%")
            
            # 计算加权平均
            comprehensive_rate = (g1 * 0.5) + (g2 * 0.15) + (g3 * 0.25) + (g4 * 0.1)
            
            print(f"\n🧮 综合增长率计算过程:")
            print(f"   g1 × 50% = {g1:.4f} × 0.5 = {g1 * 0.5:.4f}")
            print(f"   g2 × 15% = {g2:.4f} × 0.15 = {g2 * 0.15:.4f}")
            print(f"   g3 × 25% = {g3:.4f} × 0.25 = {g3 * 0.25:.4f}")
            print(f"   g4 × 10% = {g4:.4f} × 0.1 = {g4 * 0.1:.4f}")
            print(f"   ──────────────────────────────────────")
            print(f"   综合增长率 = {comprehensive_rate:.4f} = {comprehensive_rate * 100:.2f}%")
            
            print(f"\n✅ {sector_name}综合增长率计算完成: {comprehensive_rate * 100:.2f}%")
            
            return comprehensive_rate
            
        except Exception as e:
            print(f"❌ 计算{sector_name}综合增长率失败: {str(e)}")
            import traceback
            traceback.print_exc()
            return 0.05  # 返回默认5%增长率

    def _generate_sector_prediction(self, sector_id, sector_name, year, historical_data, growth_rate, industry_data):
        """生成板块预测结果"""
        try:
            print(f"\n🎯 开始生成{sector_name}{year}年预测")
            print(f"📊 输入参数:")
            print(f"   - 综合增长率: {growth_rate:.4f} ({growth_rate * 100:.2f}%)")
            print(f"   - 历史数据: {historical_data}")
            
            # 获取基准年份（最新年份）的数据
            base_year = 2024  # 假设基准年份
            base_sales_revenue = 100.0  # 默认值，单位：亿元
            base_net_profit = 10.0     # 默认值，单位：亿元
            base_profit_margin = 0.1   # 默认净利润率10%
            
            print(f"\n📈 基准数据获取:")
            print(f"   默认基准年份: {base_year}")
            print(f"   默认基准收入: {base_sales_revenue}亿元")
            print(f"   默认基准利润: {base_net_profit}亿元")
            print(f"   默认利润率: {base_profit_margin * 100:.2f}%")
            
            # 从历史数据中获取基准值
            if '销售收入' in historical_data and historical_data['销售收入']:
                latest_sales = historical_data['销售收入'][0]
                base_sales_revenue = latest_sales['value']
                base_year = latest_sales['year']
                print(f"   从历史数据获取基准收入: {base_sales_revenue}亿元 (年份: {base_year})")
            
            if '净利润' in historical_data and historical_data['净利润']:
                latest_profit = historical_data['净利润'][0]
                base_net_profit = latest_profit['value']
                if base_sales_revenue > 0:
                    base_profit_margin = base_net_profit / base_sales_revenue
                print(f"   从历史数据获取基准利润: {base_net_profit}亿元")
                print(f"   计算得出利润率: {base_profit_margin * 100:.2f}%")
            
            # 计算历史净利润率平均值
            historical_profit_margins = []
            if '销售收入' in historical_data and '净利润' in historical_data:
                sales_data = historical_data['销售收入']
                profit_data = historical_data['净利润']
                
                print(f"\n📊 计算历史净利润率平均值:")
                print(f"   销售收入记录数: {len(sales_data)}")
                print(f"   净利润记录数: {len(profit_data)}")
                
                # 按年份匹配销售收入和净利润数据
                for sales_record in sales_data:
                    year = sales_record['year']
                    sales_value = sales_record['value']
                    
                    # 查找对应年份的净利润数据
                    profit_record = next((p for p in profit_data if p['year'] == year), None)
                    if profit_record and sales_value > 0:
                        profit_margin = profit_record['value'] / sales_value
                        historical_profit_margins.append(profit_margin)
                        print(f"   {year}年: 收入{sales_value:.2f}亿, 利润{profit_record['value']:.2f}亿, 利润率{profit_margin*100:.2f}%")
                
                if historical_profit_margins:
                    avg_profit_margin = sum(historical_profit_margins) / len(historical_profit_margins)
                    print(f"   历史净利润率: {[f'{m*100:.2f}%' for m in historical_profit_margins]}")
                    print(f"   平均净利润率: {avg_profit_margin*100:.2f}%")
                    base_profit_margin = avg_profit_margin
                else:
                    print(f"   无有效历史利润率数据，使用默认值: {base_profit_margin*100:.2f}%")
            else:
                print(f"   无历史数据，使用默认利润率: {base_profit_margin*100:.2f}%")
            
            # 计算预测年份与基准年份的差距
            years_ahead = year - base_year
            print(f"\n⏰ 时间计算:")
            print(f"   预测年份: {year}")
            print(f"   基准年份: {base_year}")
            print(f"   预测跨度: {years_ahead}年")
            
            # 预测销售收入：复合增长计算
            predicted_sales_revenue = base_sales_revenue * ((1 + growth_rate) ** years_ahead)
            print(f"\n💰 销售收入预测计算:")
            print(f"   基准收入: {base_sales_revenue}亿元")
            print(f"   增长率: {growth_rate:.4f} ({growth_rate * 100:.2f}%)")
            print(f"   复合增长公式: {base_sales_revenue} × (1 + {growth_rate:.4f})^{years_ahead}")
            print(f"   复合增长系数: {(1 + growth_rate) ** years_ahead:.4f}")
            print(f"   预测收入: {predicted_sales_revenue:.2f}亿元")
            
            # 预测净利润：使用固定净利润率
            predicted_net_profit = predicted_sales_revenue * base_profit_margin
            print(f"\n💵 净利润预测计算:")
            print(f"   预测收入: {predicted_sales_revenue:.2f}亿元")
            print(f"   利润率: {base_profit_margin:.4f} ({base_profit_margin * 100:.2f}%)")
            print(f"   预测利润: {predicted_net_profit:.2f}亿元")
            
            # 构建预测结果
            prediction = {
                'sector_id': sector_id,
                'sector_name': sector_name,
                'prediction_year': year,
                'base_year': base_year,
                'base_sales_revenue': base_sales_revenue,
                'base_net_profit': base_net_profit,
                'base_profit_margin': base_profit_margin,
                'comprehensive_growth_rate': growth_rate,
                'predicted_sales_revenue': predicted_sales_revenue,
                'predicted_net_profit': predicted_net_profit,
                'predicted_profit_margin': base_profit_margin,
                'years_ahead': years_ahead,
                'growth_breakdown': {
                    'industry_cagr': industry_data.get('industry_cagr', 0.05),
                    'historical_cagr': 0.05,  # 这里可以从历史数据中获取
                    'market_stage_cagr': industry_data.get('market_stage_cagr', 0.05),
                    'strategic_growth_rate': growth_rate * 0.1 / 0.1  # 反推战略增速
                },
                'confidence_score': 0.85,  # 集团预测置信度较高
                'analysis_result': f"{sector_name}基于加权复合增长率模型预测，{year}年销售收入预计达到{predicted_sales_revenue:.2f}亿元，净利润预计{predicted_net_profit:.2f}亿元。"
            }
            
            print(f"\n📋 {sector_name}{year}年预测结果:")
            print(f"   板块ID: {sector_id}")
            print(f"   预测年份: {year}")
            print(f"   基准年份: {base_year}")
            print(f"   预测跨度: {years_ahead}年")
            print(f"   综合增长率: {growth_rate:.4f} ({growth_rate * 100:.2f}%)")
            print(f"   基准收入: {base_sales_revenue}亿元")
            print(f"   预测收入: {predicted_sales_revenue:.2f}亿元")
            print(f"   基准利润: {base_net_profit}亿元")
            print(f"   预测利润: {predicted_net_profit:.2f}亿元")
            print(f"   利润率: {base_profit_margin * 100:.2f}%")
            print(f"   置信度: {0.85 * 100:.1f}%")
            
            print(f"\n✅ {sector_name}{year}年预测生成完成")
            
            return prediction
            
        except Exception as e:
            print(f"生成{sector_name}预测失败: {str(e)}")
            return {
                'sector_id': sector_id,
                'sector_name': sector_name,
                'prediction_year': year,
                'predicted_sales_revenue': 0,
                'predicted_net_profit': 0,
                'confidence_score': 0.5,
                'analysis_result': f"{sector_name}预测生成失败"
            }

    def _calculate_group_totals(self, sector_predictions, year_range):
        """计算集团合计"""
        try:
            print(f"\n🧮 开始计算集团合计")
            print(f"📊 输入数据:")
            print(f"   - 板块预测数量: {len(sector_predictions)}")
            print(f"   - 年份范围: {year_range}")
            
            group_predictions = []
            
            for year in year_range:
                print(f"\n📅 计算{year}年集团合计:")
                
                # 获取该年份所有板块的预测
                year_predictions = [p for p in sector_predictions if p['prediction_year'] == year]
                print(f"   该年份板块预测数量: {len(year_predictions)}")
                
                # 计算合计
                total_sales_revenue = sum(p.get('predicted_sales_revenue', 0) for p in year_predictions)
                total_net_profit = sum(p.get('predicted_net_profit', 0) for p in year_predictions)
                
                print(f"   各板块收入明细:")
                for p in year_predictions:
                    print(f"     - {p['sector_name']}: {p.get('predicted_sales_revenue', 0):.2f}亿元")
                print(f"   总收入合计: {total_sales_revenue:.2f}亿元")
                
                print(f"   各板块利润明细:")
                for p in year_predictions:
                    print(f"     - {p['sector_name']}: {p.get('predicted_net_profit', 0):.2f}亿元")
                print(f"   总利润合计: {total_net_profit:.2f}亿元")
                
                print(f"   各板块综合增长率明细:")
                for p in year_predictions:
                    sector_rate = p.get('comprehensive_growth_rate', 0)
                    print(f"     - {p['sector_name']}: {sector_rate:.4f} ({sector_rate * 100:.2f}%)")
                
                # 计算集团净利润率：各板块净利润率的加权平均（按收入权重）
                group_profit_margin = 0
                if year_predictions and total_sales_revenue > 0:
                    print(f"   集团净利润率加权计算:")
                    weighted_margin_sum = 0
                    for p in year_predictions:
                        sector_revenue = p.get('predicted_sales_revenue', 0)
                        sector_profit = p.get('predicted_net_profit', 0)
                        sector_margin = sector_profit / sector_revenue if sector_revenue > 0 else 0
                        weight = sector_revenue / total_sales_revenue
                        weighted_margin_contribution = sector_margin * weight
                        weighted_margin_sum += weighted_margin_contribution
                        print(f"     - {p['sector_name']}: 收入{sector_revenue:.2f}亿, 利润{sector_profit:.2f}亿, 利润率{sector_margin*100:.2f}%, 权重{weight:.3f}, 贡献{weighted_margin_contribution*100:.2f}%")
                    group_profit_margin = weighted_margin_sum
                    print(f"   加权平均净利润率: {group_profit_margin * 100:.2f}%")
                else:
                    print(f"   集团净利润率: {group_profit_margin * 100:.2f}%")
                
                # 计算平均置信度
                avg_confidence = sum(p.get('confidence_score', 0.5) for p in year_predictions) / len(year_predictions) if year_predictions else 0.5
                print(f"   平均置信度: {avg_confidence * 100:.1f}%")
                
                # 计算集团综合增长率：各板块综合增长率的加权平均（按收入权重）
                group_comprehensive_rate = 0
                if year_predictions and total_sales_revenue > 0:
                    print(f"   集团综合增长率加权计算:")
                    weighted_sum = 0
                    for p in year_predictions:
                        sector_revenue = p.get('predicted_sales_revenue', 0)
                        sector_rate = p.get('comprehensive_growth_rate', 0)
                        weight = sector_revenue / total_sales_revenue
                        weighted_contribution = sector_rate * weight
                        weighted_sum += weighted_contribution
                        print(f"     - {p['sector_name']}: 收入{sector_revenue:.2f}亿, 权重{weight:.3f}, 增长率{sector_rate:.4f}, 贡献{weighted_contribution:.4f}")
                    group_comprehensive_rate = weighted_sum
                    print(f"   加权平均结果: {group_comprehensive_rate:.4f}")
                
                print(f"   集团综合增长率: {group_comprehensive_rate:.4f} ({group_comprehensive_rate * 100:.2f}%)")
                
                group_prediction = {
                    'sector_id': 'group_total',
                    'sector_name': '集团合计',
                    'prediction_year': year,
                    'predicted_sales_revenue': total_sales_revenue,
                    'predicted_net_profit': total_net_profit,
                    'predicted_profit_margin': group_profit_margin,
                    'comprehensive_growth_rate': group_comprehensive_rate,  # 添加集团综合增长率
                    'confidence_score': avg_confidence,
                    'analysis_result': f"集团{year}年预计实现销售收入{total_sales_revenue:.2f}亿元，净利润{total_net_profit:.2f}亿元，净利润率{group_profit_margin*100:.2f}%，综合增长率{group_comprehensive_rate*100:.2f}%。",
                    'sector_breakdown': year_predictions
                }
                
                group_predictions.append(group_prediction)
                print(f"   ✅ {year}年集团合计计算完成")
            
            print(f"\n✅ 集团合计计算完成，共生成 {len(group_predictions)} 条集团合计记录")
            
            return group_predictions
            
        except Exception as e:
            print(f"❌ 计算集团合计失败: {str(e)}")
            import traceback
            traceback.print_exc()
            return []

